package com.ccit.service.impl;

import com.ccit.dao.AttendanceDao;
import com.ccit.dao.UserDao;
import com.ccit.domain.Attendance;
import com.ccit.domain.AttendanceType;
import com.ccit.domain.PageBean;
import com.ccit.domain.Time;
import com.ccit.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


@Service
public class AttendanceServiceImpl implements AttendanceService {

    @Autowired
    private AttendanceDao attendanceDao;

    @Autowired
    private UserDao userDao;



    @Override
    public boolean add(AttendanceType attendance) {
        return attendanceDao.add(attendance) > 0;
    }

    @Override
    public List<Attendance> getById(Integer id) {
        return attendanceDao.getById(id);
    }

    @Override
    public boolean delete(Integer id) {

        return attendanceDao.delete(id) >0;
    }

    @Override
    public boolean deleteByIds(List<Integer> ids) {
        return attendanceDao.deleteByIds(ids) >0;
    }

    @Override
    public List<Attendance> selectAll() {
        return attendanceDao.selectAll();
    }

    @Override
    public List<AttendanceType> selectByDays(Integer id) {

//        List<AttendanceType> attendances = attendanceDao.selectByDays(id);

//        Map<String, Integer> statusCountMap = new HashMap<>();
//        for (Attendance attendance : attendances) {
//            String status = attendance.getStatus();
//            if (statusCountMap.containsKey(status)) {
//                // 如果状态已经在Map中存在，则增加计数
//                int count = statusCountMap.get(status);
//                statusCountMap.put(status, count + 1);
//            } else {
//                // 如果状态还不存在于Map中，则将其添加到Map并设置计数为1
//                statusCountMap.put(status, 1);
//            }
//        }
//        // 输出不同状态的计数
//        for (Map.Entry<String, Integer> entry : statusCountMap.entrySet()) {
//            String status = entry.getKey();
//            int count = entry.getValue();
//            System.out.println("状态：" + status + "，次数：" + count);
//        }
//
//        int normalCount = 0;//正常
//        int lateCount = 0;//迟到
//        int earlyCount = 0;//早退
//        int absentCount = 0;//缺勤
//
//        for (Attendance attendance : attendances) {
//            String status = attendance.getStatus();
//            if (status.equals("正常")) {
//                normalCount++;
//            } else if (status.equals("迟到")) {
//                lateCount++;
//            } else if (status.equals("早退")) {
//                earlyCount++;
//            } else if (status.equals("缺勤")) {
//                absentCount++;
//            }
//        }
//
//        System.out.println("正常次数：" + normalCount);
//        System.out.println("迟到次数：" + lateCount);
//        System.out.println("早退次数：" + earlyCount);
//        System.out.println("缺勤次数：" + absentCount);

//        System.out.println(attendances);

        return attendanceDao.selectByDays(id);
    }

    @Override
    public boolean update(AttendanceType attendance) {
        return attendanceDao.update(attendance) > 0;
    }

    @Override
    public PageBean<Attendance> selectByPage(int currentPage, int pageSize) {
        //计算开始索引
        int begin = (currentPage-1 ) * pageSize;
        //计算查询条目数
        int size = pageSize;
        //查询数据记录
        List<Attendance> attendances = attendanceDao.selectByPage(begin, size);
        //查询总记录数
        int totalCount = attendanceDao.selectTotalCount();
        //封装pageBean对象
        PageBean<Attendance> pageBean = new PageBean<>();
        pageBean.setRows(attendances);  //rows
        pageBean.setTotalCount(totalCount);
        return pageBean;
    }

    @Override
    public PageBean<Attendance> selectByPageAndCondition(int currentPage, int pageSize, Attendance attendance) {
        // 计算开始索引
        int begin = (currentPage - 1) * pageSize;
        // 计算查询条目数
        int size = pageSize;
        // 查询数据记录
        List<Attendance> attendances = attendanceDao.selectByPageAndCondition(attendance,begin, size);
        // 查询符合条件的总记录数
        int totalCount = attendanceDao.selectTotalCountByCondition(attendance);
        // 封装 PageBean 对象
        PageBean<Attendance> pageBean = new PageBean<>();
        pageBean.setRows(attendances); // 设置数据列表
        pageBean.setTotalCount(totalCount); // 设置总记录数
        return pageBean;
    }

    @Override
    public Boolean punchCard(AttendanceType attendance) {
        System.out.println("attendance");
        // 获取打卡类型上班 '1'或者下班 '2'
        String type = attendance.getType();
        System.out.println("type " + type);
        if (type.equals("1")) {
//            String checkIn = attendance.getCheckIn();
            // 插入数据
//            System.out.println("add " + attendance);
            return attendanceDao.add(attendance) > 0;
        } else {
//            System.out.println("update " + attendance);
            // 根据 employeeId 和 checkDate 去更新 checkOut
            return attendanceDao.update(attendance) > 0;
        }
    }

    public AttendanceType getPunchRecord(Integer employeeId, String checkDate) {
        AttendanceType attendanceType = attendanceDao.findByEmployeeIdAndDate(employeeId, checkDate);
        System.out.println(attendanceType);
        String checkIn = attendanceType.getCheckIn();
        String checkOut = attendanceType.getCheckOut();
//        if (checkIn != null && checkOut != null) {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            LocalDateTime checkInTime = LocalDateTime.parse(checkIn, formatter);
//            LocalDateTime checkOutTime = LocalDateTime.parse(checkOut, formatter);
//
//            List<Time> time = userDao.getTime();
//            System.out.println(time);
//
//            LocalDateTime morningStart = LocalDateTime.of(
//                    checkInTime.toLocalDate(),
//                    LocalTime.of(8, 30, 0)
//            );
//            LocalDateTime afternoonEnd = LocalDateTime.of(
//                    checkOutTime.toLocalDate(),
//                    LocalTime.of(17, 30, 0)
//            );
//            LocalDateTime morningEnd = LocalDateTime.of(
//                    checkInTime.toLocalDate(),
//                    LocalTime.of(8, 40, 0)
//            );
//            LocalDateTime afternoonStart = LocalDateTime.of(
//                    checkOutTime.toLocalDate(),
//                    LocalTime.of(17, 0, 0)
//            );
//            String attendanceStatus;
//            if (checkInTime.isBefore(morningStart) && checkOutTime.isAfter(afternoonEnd)) {
//                attendanceStatus = "正常";
//            } else if (checkInTime.isAfter(morningStart) && checkInTime.isBefore(morningEnd) && checkOutTime.isAfter(afternoonEnd)) {
//                attendanceStatus = "迟到";
//            } else if (checkInTime.isBefore(morningStart) && checkOutTime.isAfter(afternoonStart) && checkOutTime.isBefore(afternoonEnd)) {
//                attendanceStatus = "早退";
//            } else {
//                attendanceStatus = "缺勤";
//            }
//            attendanceType.setStatus(attendanceStatus);
//            System.out.println(attendanceStatus);
//            System.out.println("asd:"+ attendanceType);
//            attendanceDao.update(attendanceType);
//        }
        if (checkIn != null && checkOut != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime checkInTime = LocalDateTime.parse(checkIn, formatter);
            LocalDateTime checkOutTime = LocalDateTime.parse(checkOut, formatter);

            List<Time> time = userDao.getTime();

            LocalDateTime morningStart = LocalDateTime.of(
                    checkInTime.toLocalDate(),
                    LocalTime.parse(time.get(0).getMorningStart())
            );
            LocalDateTime afternoonEnd = LocalDateTime.of(
                    checkOutTime.toLocalDate(),
                    LocalTime.parse(time.get(0).getAfternoonEnd())
            );
            LocalDateTime morningEnd = LocalDateTime.of(
                    checkInTime.toLocalDate(),
                    LocalTime.parse(time.get(0).getMorningEnd())
            );
            LocalDateTime afternoonStart = LocalDateTime.of(
                    checkOutTime.toLocalDate(),
                    LocalTime.parse(time.get(0).getAfternoonStart())
            );

            String attendanceStatus;
            if (checkInTime.isBefore(morningStart) && checkOutTime.isAfter(afternoonEnd)) {
                attendanceStatus = "正常";
            } else if (checkInTime.isAfter(morningStart) && checkInTime.isBefore(morningEnd) && checkOutTime.isAfter(afternoonEnd)) {
                attendanceStatus = "迟到";
            } else if (checkInTime.isBefore(morningStart) && checkOutTime.isAfter(afternoonStart) && checkOutTime.isBefore(afternoonEnd)) {
                attendanceStatus = "早退";
            } else {
                attendanceStatus = "缺勤";
            }

            attendanceType.setStatus(attendanceStatus);
//            System.out.println(attendanceStatus);
//            System.out.println("asd:" + attendanceType);
            attendanceDao.update(attendanceType);
        }
        return attendanceType;
    }


    @Override
    public List<AttendanceType> getAttendanceByDate(String checkDate) {
        return attendanceDao.findByEmployeeDate(checkDate);
    }

    @Override
    public List<AttendanceType> selectByEmployeeIdAndDate() {
        return attendanceDao.selectByEmployeeIdAndDate();
    }


}
